package com.tx.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tx.entity.*;
import com.tx.service.FileInfoService;
import com.tx.utils.FileUtil;
import com.tx.utils.StringUtil;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

/**
 * @Author: tcx
 * @description: 文件管理控制器
 * @Date: 2019/11/10
 **/
@Controller("fileInfoController")
@RequestMapping("/fileInfo")
public class FileInfoController {
    @Autowired
    private FileInfoService fileInfoService;

    /* *
     * @description:  打开下载文件列表
     * @author tcx
     * @date 2019/11/13
     * @param map
     * @return java.lang.String
     */
    @RequestMapping(value = "/to_list",params = "currentPage")
    public String toFileList(Map<String,Object> map,Integer currentPage){
        Page page = new Page();
        page.setCurrentPage(currentPage);
        //将文件列表传递到页面
        Result result = fileInfoService.getFileByPage(page);
        page = result.getPage();
        List<FileInfo> list = result.getList();
        map.put("flist",list);
        map.put("pageInfo",page);
        //将分页信息传递到页面
        return "/filelist";
    }
    /* *
     * @description:  根据关键字搜索文件
     * @author tcx
     * @date 2019/11/13
     * @param map
     * @param currentPage
     * @param title
     * @return java.lang.String
     */
    @RequestMapping("/listKey")
    public String blogKey(Map<String,Object> map, @RequestParam("currentPage") Integer currentPage, @RequestParam String title){
        Page page = new Page();
        page.setCurrentPage(currentPage);
        //将博客信息传递到博客列表传递到页面
        Result result = fileInfoService.getKeyPage(title,page);
        page = result.getPage();
        List<FileInfo> list = result.getList();
        map.put("flist",list);
        map.put("pageInfo",page);
        map.put("key",title);
        //将分页信息传递到页面
        return "/filelistByKey";
    }

    /* *
     * @description:  打开我的文件页面
     * @author tcx
     * @date 2019/11/11
     * @param map
     * @param session
     * @return java.lang.String
     */
    @RequestMapping(value = "/student/to_list")
    public String toList(){

        return "/student_filelist";
    }

    /* *
     * @description: 上传文件
     * @author tcx
     * @date 2019/11/10
     * @param uploadFile
     * @param request
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping("/student/add")
    public String upload(@RequestParam("uploadFile") MultipartFile uploadFile, HttpServletRequest request,FileInfo fileInfo,HttpSession session) throws IOException {
        //从session中获取当前登录用户
        User user = (User) session.getAttribute("user");
        Map<String, Object> map = new HashMap<String, Object>();
        Gson gson = new Gson();
        if(user!=null){
            //获得文件
            byte[] buf = uploadFile.getBytes();
            //获取文件名    a.txt
            String originalFileName = uploadFile.getOriginalFilename();
            //获取项目根路径
            String fileUrl = "/";
            fileUrl = request.getServletContext().getRealPath(fileUrl);
            //向url地址存储文件
            String url = FileUtil.writeFileToUrl(uploadFile, fileUrl,originalFileName);
            //向保存文件信息
            fileInfo.setuId(user.getuId());//设置上传文件用户id
            fileInfo.setfSize(FileUtil.readableFileSize(buf.length));//存储文件大小
            fileInfo.setfPath(url);//文件存储路径
            //得到文件类型
            String fType = FileUtil.getType(url);
            fileInfo.setfTypeImage(FileUtil.getImage(fType));
            fileInfo.setfType(fType);//文件类型
            //调用业务层
            int resultTotal=fileInfoService.add(fileInfo);
            if (resultTotal > 0) {
                map.put("code",200);
                map.put("msg","添加成功");
            } else {
                map.put("code",-1);
                map.put("msg","添加失败");
            }
        }else{
            map.put("code",-2);
            map.put("msg","登录失效");
        }
        return gson.toJson(map);
    }


    /* *
     * @description:  删除文件
     * @author tcx
     * @date 2019/11/11
     * @param fId
     * @return java.lang.String
     */
  /*  @RequestMapping(value = "/student/remove",params = "fId")
    public String remove(Integer fId){
        //获得文件信息
        FileInfo fileInfo = fileInfoService.get(fId);
        //从数据库删除文件
        fileInfoService.remove(fId);
        //从本地删除文件
        FileUtil.deleteFile(fileInfo.getfPath());
        return "redirect:/fileInfo/student/to_list.do?currentPage=1";
    }*/
  /* *
   * @description:  删除文件
   * @author tcx
   * @date 2019/11/22
   * @param request
   * @return java.lang.String
   */
    @ResponseBody
    @RequestMapping("/student/remove")
    public String remove(HttpServletRequest request){
        Integer fId = Integer.parseInt(request.getParameter("fId"));
        //获得文件信息
        FileInfo fileInfo = fileInfoService.get(fId);
        //从数据库删除文件
        fileInfoService.remove(fId);
        //从本地删除文件
        FileUtil.deleteFile(fileInfo.getfPath());
        JSONObject json = new JSONObject();
        return json.toString();
    }
    /* *
     * @description:  打开添加界面
     * @author tcx
     * @date 2019/11/11
     * @param fId
     * @param map
     * @return java.lang.String
     */
    @RequestMapping(value = "/student/to_add")
    public String add(){
        return "student_fileAdd";
    }
    /* *
     * @description:  打开修改界面
     * @author tcx
     * @date 2019/11/11
     * @param fId
     * @param map
     * @return java.lang.String
     */
    @RequestMapping(value = "/student/to_edit",params = "fId")
    public String edit(Integer fId,Map<String,Object> map){
        //获取文件数据
        map.put("file",fileInfoService.get(fId));
        return "student_fileedit";
    }
    /* *
     * @description:  修改文件信息
     * @author tcx
     * @date 2019/11/11
     * @param fileInfo
     * @return java.lang.String
     */
    @RequestMapping("/student/edit")
    public String update(MultipartFile uploadFile, HttpServletRequest request,FileInfo fileInfo) throws IOException {
        //如果用户有新上传文件，修改文件路径并删除源文件
        if (uploadFile.getBytes().length!=0){
            //获得文件
            byte[] buf = uploadFile.getBytes();
            //获取文件名    a.txt
            String originalFileName = uploadFile.getOriginalFilename();
            //获取项目根路径
            String fileUrl = "/";
            fileUrl = request.getServletContext().getRealPath(fileUrl);
            //向url地址存储文件
            String url = FileUtil.writeFileToUrl(uploadFile, fileUrl,originalFileName);
            //删除源文件
            FileUtil.deleteFile(fileInfo.getfPath());
            //向保存文件信息
            fileInfo.setfSize(FileUtil.readableFileSize(buf.length));//存储文件大小
            fileInfo.setfPath(url);//文件存储路径
            fileInfo.setfType(FileUtil.getType(url));//文件类型
        }
        fileInfoService.edit(fileInfo);
        return "redirect:/fileInfo/student/to_list.do?currentPage=1";
    }
    /* *
     * @description:打开下载文件的界面
     * @author tcx
     * @date 2019/11/11
     * @param map
     * @return java.lang.String
     */
    @RequestMapping(value = "/to_fileInfo",params = "fId")
    public String tofileContent(Integer fId,Map<String,Object> map){
        //查询出文件详情返回给界面
        map.put("fileinfo",fileInfoService.get(fId));
        //打开文件详情界面
        return "/fileInfo";
    }
    /* *
     * @description:  点击下载文件
     * @author tcx
     * @date 2019/11/11
     * @param fId
     * @return org.springframework.http.ResponseEntity<byte[]>
     */
    @RequestMapping("/student/download")
    public ResponseEntity<byte[]> download(Integer fId) throws Exception {
            FileInfo fileInfo = fileInfoService.get(fId);
            String fileUrl = fileInfo.getfPath();
            String fileName = fileInfo.getfName()+"."+fileInfo.getfType();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "iso8859-1"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(fileUrl)), headers, HttpStatus.CREATED);
            return entity;
    }

/********************************************admin管理界面*********************************************/


    /*用户文件列表*/
    @RequestMapping("/student/list")
    @ResponseBody
    public String student_list(@RequestParam(value = "page", required = false) Integer currentPage,
                       @RequestParam(value = "limit", required = false) Integer rows,
                       @RequestParam(value = "keywords", required = false) String keywords,
                       @RequestParam(value = "startTime", required = false) String startTime,
                       @RequestParam(value = "endTime", required = false) String endTime,HttpSession session){
        User user = (User) session.getAttribute("user");
        Page pageBean = new Page();
        pageBean.setCurrentPage(currentPage);//设置当前页
        pageBean.setEveryPage(rows);//设置每页显示数量
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("start", pageBean.getStart());//设置起始页
        map.put("size", pageBean.getEveryPage());//设置页面大小
        map.put("q", StringUtil.formatLike(keywords));
        map.put("startTime", startTime);
        map.put("endTime", StringUtil.formatEndTime(endTime));
        map.put("uId", user.getuId());
        List<FileInfo> list = fileInfoService.list(map);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
        Integer total = fileInfoService.getTotal(map);//获得总数据
        map.clear();
        if(list!=null){
            map.put("data", list);
            map.put("count", total);
            map.put("code", 0);
            map.put("msg", "");
        }else{
            map.put("data", list);
            map.put("count", total);
            map.put("code", 1);
            map.put("msg", "");
        }
        return  gson.toJson(map);
    }
    /*修改文件名*/
    @ResponseBody
    @RequestMapping("/teacher/admin_update")
    public String adminupdate(FileInfo fileInfo, HttpSession session){
        int resultTotal = fileInfoService.edit(fileInfo);
        Map<String, Object> map = new HashMap<String, Object>();
        Gson gson = new Gson();
        if (resultTotal > 0) {
            map.put("code",0);
            map.put("msg","修改成功");
        } else {
            map.put("code",-1);
            map.put("msg","修改失败");
        }
        return gson.toJson(map);
    }
    /* *
     * @description:  删除文件
     * @author tcx
     * @date 2020/04/05
     * @param request
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping("/teacher/admin_delete")
    public String deleteFile(HttpServletRequest request){
        //Integer uId = Integer.parseInt(request.getParameter("uId"));
        String[] idsStr = request.getParameter("ids").split(",");
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < idsStr.length; i++) {
            fileInfoService.remove(Integer.parseInt(idsStr[i]));
        }
        map.put("msg", 200);
        return  gson.toJson(map);
    }
}
